package yxy.game.pm2.command.soloride;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.SoloRideMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.battle.BattleHandle;
import yxy.game.pm2.module.battle.BattleModule;
import yxy.game.pm2.module.soloride.SoloRideModule;

/** 千里走单骑 千里走单骑战斗结算 */
@MessageType(proto = Command.SoloRideChanllengeBattleClear, classtype = SoloRideMessage.SoloRideChanllengeBattleClearRequest.class)
public class CMD_SoloRideChanllengeBattleClear extends Command<SoloRideMessage.SoloRideChanllengeBattleClearRequest> {

	@Override
	public void execute(MessageSource messageSource, SoloRideMessage.SoloRideChanllengeBattleClearRequest request) {
		String playerCode = messageSource.getTag();
		String battleCode = request.getBattleCode();

		SoloRideMessage.SoloRideChanllengeBattleClearResponse.Builder response = SoloRideMessage.SoloRideChanllengeBattleClearResponse.newBuilder();

		SoloRideModule soloRideModule = SoloRideModule.get(playerCode);
		if (soloRideModule == null) {
			send(messageSource, response, Result.ModuleNotOpen);// 模块没开启
			return;
		}
		try {
			if (soloRideModule.tryLock()) {
				if (!soloRideModule.getBattles().contains(battleCode)) {
					send(messageSource, response, Result.ParamError);// 战斗已结算
					return;
				}

				BattleModule battleModule = BattleModule.get(playerCode, battleCode);
				if (battleModule.isSettled()) {
					send(messageSource, response, Result.BattleHasSettled);// 战斗已结算
					return;
				}

				battleModule.getSettlement().settle();

				response.setInfo(new BattleHandle().battleClear(battleModule));
				response.addAllRewards(new CurrencyHandle().packItems(Currency.merge(battleModule.getSettlement().reward())));

				send(messageSource, response, Result.Success);
//				TaskHandle.handle(playerCode, TaskType.统计型_副本_神将试炼_次数, 1);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			soloRideModule.unlock();
		}
	}

	private void send(MessageSource messageSource, SoloRideMessage.SoloRideChanllengeBattleClearResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}